package com.sychip.fhc.app.wsn.screen


import android.graphics.RectF
import androidx.annotation.IntRange
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.lifecycle.viewModelScope
import com.fhc.base.Async
import com.fhc.base.EventType
import com.fhc.base.FhcFlowEventBus
import com.fhc.base.FlowEventBusData
import com.fhc.base.RssiDataFromDto
import com.sychip.fhc.MainApplication
import com.sychip.fhc.app.data.repo.WsnDeviceRepo
import com.sychip.fhc.app.data.repo.WsnDeviceRssiRepo
import com.sychip.fhc.app.data.repo.WsnRssiHisRepo
import com.sychip.fhc.app.data.source.dto.DevType
import com.sychip.fhc.app.data.source.dto.WsnDeviceRssiDto
import com.sychip.fhc.app.pref.AppSetting
import com.sychip.fhc.app.pref.PrefDataStoreIf
import com.sychip.fhc.app.todo.R
import com.sychip.fhc.app.wsn.common.RouteJoin
import com.sychip.fhc.app.wsn.common.util.DeviceLayoutHelper
import com.sychip.fhc.app.wsn.nav.RouterAvgPerDto
import com.sychip.fhc.base.CommonUiState
import com.sychip.fhc.base.UiStatus
import com.sychip.fhc.di.DefaultDispatcher
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted.Companion.Eagerly
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import timber.log.Timber
import javax.inject.Inject


@Retention(AnnotationRetention.SOURCE)
@Target(AnnotationTarget.VALUE_PARAMETER)
annotation class MapDevSizeRange(
    val min: Long = 1000,
    val max: Long = Long.MAX_VALUE
)


data class MapDeviceLineDto   (
    val wsnDev: WsnDeviceRssiDto,
    var fromPoint: Offset = Offset.Zero,
    var toPoint: Offset = Offset.Zero,
    var middlePoint: Offset = Offset.Zero,
    var rect: RectF = RectF(0f,0f,0f,0f),
    var isNoUpdate60s: Boolean = false,
    var isUpdatedIn1s: Boolean = false,
    var isLineShow: Boolean = true,
    var isUnFocused: Boolean = false,
)
data class MapDeviceDto(
    val usbId: String = "",
    val devId: String = "",
    var name: String = "",
    var offsetX: Float = 0f,
    var offsetY: Float = 0f,
    var lastData: String = "",
    var devType: String = "",
    var unHighlight: Boolean = false,
    var rssiUpdated: Boolean = false,
    var isNoUpdate60s: Boolean = false,
    var bgColor: Color = Color.White,
    var txtColor: Color = Color.Black,
    )



/**
 * ViewModel for the WsnMap screen.
 */
@HiltViewModel
class WsnMapViewModel @Inject constructor(
    app : MainApplication,
    override val devRepo: WsnDeviceRepo,
    override val rssiRepo: WsnDeviceRssiRepo,
    override  val rssiHisRepo: WsnRssiHisRepo,
    override val prefDataStore: PrefDataStoreIf,
    @DefaultDispatcher private val dispatcher: CoroutineDispatcher,
) :  WsnBaseViewModel(app, prefDataStore, rssiRepo, devRepo, rssiHisRepo) {

    private var _mapW = 0
    private var _mapH = 0
    private var _devW = 0
    private var _devH = 0

    private val listMutex = Mutex()
    private var posUtils: DeviceLayoutHelper = DeviceLayoutHelper()
    private var resetDeviceStateJob: Job? = null

    fun startResetDeviceStateJob() {
        resetDeviceStateJob?.cancel()
        resetDeviceStateJob = resetLineDeviceState()
    }
    private fun observeAppSetting() {
        prefDataStore.getAppSettings().map {
            startResetDeviceStateJob()
        }.stateIn(
            scope = viewModelScope,
            started = Eagerly,
            initialValue = mutableStateOf<AppSetting?>(null)
        )
    }
    private fun observeAvgPer() {
        viewModelScope.launch {
            FhcFlowEventBus.subscribe<FlowEventBusData> { event ->
                if (event.dataType == EventType.AvgPer) {
                    launch{
                        listMutex.withLock {
                            val avgPerDto = event.dataObj as RouterAvgPerDto
                            val oldAvgPerDto = _avgPerList.find { it.fromDevId == avgPerDto.fromDevId && it.toDevId == avgPerDto.toDevId }
                            if (oldAvgPerDto == null) {
                                _avgPerList.add(avgPerDto)
                            } else {
                                oldAvgPerDto.avg = avgPerDto.avg
                                oldAvgPerDto.per = avgPerDto.per
                            }
                            _avgPerDataFlow.update { _avgPerList.toMutableList() }
                        }
                    }
                }
            }
        }
    }

    private val _lineFlow = MutableStateFlow<MutableList<MapDeviceLineDto>>(mutableStateListOf())
    val lineFlow: StateFlow<MutableList<MapDeviceLineDto>> = _lineFlow.asStateFlow()


    //监测RSSI数据变化，变化时如果UI已发起过device查询，则_devices有结果，此时根据device的坐标转换为一个line对象，并更新到lineFlow
    private fun handleLastRssiAsync(devs: List<WsnDeviceRssiDto>?): Async<List<WsnDeviceRssiDto>> {
        if (devs == null) {
            return Async.Error(R.string.task_not_found)
        }
        return Async.Success(devs)
    }

    init {
        //这里初始化清空过滤内容
        updateFilterDto(FilterDto())

        observerFilterDto(afterFilterChanged = {
            Timber.i("observerFilterDto    getDevFilterAllRoutes")
            getDevFilterAllRoutes()
            Timber.i("1111111111111  init    filterLineAndDevice")
            filterLineAndDevice()
        })
        viewModelScope.launch {
            try {
                prefDataStore.getMapSizeChangeReminderMe()
                    .catch { e ->
                        Timber.e("getMapSizeChangeReminderMe Error getting preference %s ",e.message)
                    }.collect { result ->
                        _remindFlow.update { result }
                    }
            } catch (e: Exception) {
                Timber.e("getMapSizeChangeReminderMe Error getting preference %s ",e.message)
            }
        }
//        prefDataStore.getMapSizeChangeReminderMe().map { result ->
//            _remindFlow.update { result }
//        }.launchIn(viewModelScope)

        rssiRepo.observeLastRssi(usbId).map {
            getDevFilterAllRoutes()
            handleLastRssiAsync(it)
        }.map { task ->
            when (task) {
                Async.Loading -> mutableStateListOf()
                is Async.Error -> mutableStateListOf()
                is Async.Success -> {
                    _rssiLastList.clear()
                    _rssiLastList.addAll(task.data)
                    reloadDevice()
                    if (_rssiLastList.isEmpty()) {
                        _devices.clear()
                        _devFlow.update { CommonUiState(status = UiStatus.Success, dataList = _devices) }
                    } else {
//                        Timber.e("observeLastRssi  >>>  _devices.isNotEmpty():%s   _rssiLastList: %s ",_devices.isNotEmpty(),_rssiLastList.size)
                        if (_devices.isNotEmpty()) {
                            val newList = mutableListOf<MapDeviceLineDto>()
                            _rssiLastList.forEach { rssi ->
                                rssiToLine(rssi)?.let { lineDto ->
                                    newList.add(lineDto)
                                }
                            }
                            _lineFlow.update {
                                newList
                            }
                        }
                    }
                    _rssiLastList.toList()
                }
            }
        }.stateIn(
            scope = viewModelScope,
            started = Eagerly,
            initialValue = mutableStateListOf<MapDeviceLineDto>()
        )

//        rssiRepo.observeOldestDataFrom(usbId, appInitTime).map { it ->
//            synchronized(_rssiStateLock) {
//                _rssiState.oldestRoute.clear()
//                _rssiState.oldestRoute.addAll(it)
//            }
//        }.stateIn(
//            scope = viewModelScope,
//            started = Eagerly,
//            initialValue = mutableStateListOf<MapDeviceLineDto>()
//        )

        observeAppSetting()
        observeAvgPer()
    }
    private var _avgPerList: MutableList<RouterAvgPerDto> = mutableStateListOf()
    private val _avgPerDataFlow: MutableStateFlow<MutableList<RouterAvgPerDto>> = MutableStateFlow(mutableStateListOf())
    val avgPerDataFlow: StateFlow<MutableList<RouterAvgPerDto>> = _avgPerDataFlow.asStateFlow()


    private var _devices: MutableList<MapDeviceDto> = mutableStateListOf()  //devFlow不及时
    private val _devFlow = MutableStateFlow<CommonUiState<MapDeviceDto>>(CommonUiState())
    val devFlow: StateFlow<CommonUiState<MapDeviceDto>> = _devFlow.asStateFlow()
    private val _devFilterFlow: MutableStateFlow<MutableList<MapDeviceDto>> = MutableStateFlow(mutableStateListOf())
    val devFilterFlow: StateFlow<MutableList<MapDeviceDto>> = _devFilterFlow.asStateFlow()
    private var _rssiLastList: MutableList<WsnDeviceRssiDto> = mutableStateListOf()


    //必须在设置容器，设备等大小后再获取设备，才可以计算device摆放的位置，因为如果USB已经插上，UI还未渲染时收到数据就不好处理，
    // 所以没用监测的方式观察device数据
    private fun reloadDevice() {
        viewModelScope.launch {
            val result = devRepo.getWsnDevices(usbId)
//            Timber.e("reloadDevice  getAllWsnDevices >>>  result:  %s ",result.size)

            listMutex.withLock {
                result.forEach { dev ->
                    val exist = _devices.find { it.devId == dev.devId }
                    if (exist == null) {
                        //TODO 在这里触发_devices
                        val device = MapDeviceDto("", dev.devId, dev.name,  dev.offsetX, dev.offsetY, dev.lastData, dev.devType)
                        if(device.devType == DevType.Gateway.name) {
                            device.bgColor = Color(0xFFf56c6c)
                            device.txtColor = Color.Black
                        }else if(device.devType == DevType.Repeater.name) {
                            device.bgColor = Color(0xFF409eff)
                            device.txtColor = Color.White
                        }
                        _devices.add(device)
                    }
                }
            }

            val devPos = posUtils.layoutDevices(_devices)
            devPos.forEach { dev ->
                devRepo.updateOffset(usbId = usbId, devId = dev.devId, offsetX = dev.offsetX, offsetY = dev.offsetY)
                val oldDev = _devices.find { it -> it.devId == dev.devId }

                if (oldDev != null) {
                    oldDev.offsetX = dev.offsetX
                    oldDev.offsetY = dev.offsetY
                }
            }
            _devFlow.update { CommonUiState(status = UiStatus.Success, dataList = _devices) }
            val newList = mutableListOf<MapDeviceLineDto>()
            _rssiLastList.forEach { rssi ->
                rssiToLine(rssi)?.let {
                    newList.add(it)
                }
            }
            _lineFlow.update {
                newList
            }
            Timber.i("1111111111111  reloadDevice    filterLineAndDevice")
            filterLineAndDevice()
        }
    }


    private fun rssiToLine(rssi: WsnDeviceRssiDto): MapDeviceLineDto? {
        val fromDev = _devices.find { it.devId == rssi.fromDevId }
        val toDev = _devices.find { it.devId == rssi.toDevId }
        if (fromDev != null && toDev != null) {
            val fromPoint = Offset(x = fromDev.offsetX + _devW / 2, y = fromDev.offsetY + _devH / 2)
            val toPoint = Offset(x = toDev.offsetX + _devW / 2, y = toDev.offsetY + _devH / 2)

            val dx = fromPoint.x - toPoint.x
            val dy = fromPoint.y - toPoint.y
            val middle = Offset(
                toPoint.x + dx / 2f,
                toPoint.y + dy / 2f
            )
            return MapDeviceLineDto(rssi, fromPoint, toPoint, middle)
        }
        return null
    }


    private val _remindDeviceBeyondMapFlow = MutableStateFlow(false)
    val remindDeviceBeyondMapFlow: StateFlow<Boolean> = _remindDeviceBeyondMapFlow.asStateFlow()
    fun setMapDevSize(
        @MapDevSizeRange(min = 100) mapW: Int,
        @MapDevSizeRange(min = 100) mapH: Int,
        @IntRange(from = 100) devW: Int,
        @IntRange(from = 100) devH: Int
    ) {
        if (mapW == _mapW && mapH == _mapH && devW == _devW && devH == _devH) return
        _mapW = mapW
        _mapH = mapH
        _devW = devW
        _devH = devH
//        Timber.i("  这里 setMapDevSize1111   %s     %s  %s   %s   %s", _remindFlow.value, _mapW, _mapH, _devW, _devH)
        _remindDeviceBeyondMapFlow.update { false }

        posUtils = DeviceLayoutHelper(_mapW, _mapH, _devW, _devH)
        reloadDevice()

        _devices.forEach {
            if (it.offsetX > _mapW - _devW || it.offsetY > _mapH - _devH) {
                if (_remindFlow.value) _remindDeviceBeyondMapFlow.update { true }
                Timber.i("  这里 setMapDevSize2222   %s     %s   %s   ", it.devId, _remindFlow.value, _remindDeviceBeyondMapFlow.value)

                return@forEach
            }
        }
    }

    fun updateDeviceXY(dto: MapDeviceDto, offsetX: Float = 0f, offsetY: Float = 0f) {
//        Timber.i("   updateDeviceXY 6666666666666666666   %s    %s--%s      ", dto.devId, dto.offsetX, dto.offsetY)
        viewModelScope.launch {
            devRepo.updateOffset(usbId = usbId, devId = dto.devId, offsetX = offsetX, offsetY = offsetY)
            updateLineXY(dto.devId, offsetX, offsetY)
        }
    }


    private fun updateLineXY(devId: String, offsetX: Float, offsetY: Float) {
        val dev = _devices.find { it -> it.devId == devId }
        if (dev != null) {
            dev.offsetX = offsetX
            dev.offsetY = offsetY
        }
        val newList = lineFlow.value.toMutableList()  // 创建临时副本
        for (i in 0 until newList.size) {
            val isUpdateFrom = newList[i].wsnDev.fromDevId == devId
            val isUpdateTo = newList[i].wsnDev.toDevId == devId
            var fromPoint: Offset
            var toPoint: Offset
            if (isUpdateFrom) {
                fromPoint = Offset(offsetX + _devW / 2, offsetY + _devH / 2)
                toPoint = newList[i].toPoint
            } else if (isUpdateTo) {
                fromPoint = newList[i].fromPoint
                toPoint = Offset(offsetX + _devW / 2, offsetY + _devH / 2)
            } else {
                continue
            }
            val dx = fromPoint.x - toPoint.x
            val dy = fromPoint.y - toPoint.y
            val middle = Offset(
                toPoint.x + dx / 2f,
                toPoint.y + dy / 2f
            )
            newList[i] = newList[i].copy(fromPoint = fromPoint, toPoint = toPoint, middlePoint = middle)
        }
        _lineFlow.update {
            newList
        }
        Timber.i("1111111111111  updateLineXY    filterLineAndDevice")
        filterLineAndDevice()
    }


    private val _remindFlow = MutableStateFlow(true)

    //    val remindFlow: StateFlow<Boolean> = _remindFlow.asStateFlow()
    fun doNotRemind() = viewModelScope.launch {
        _remindFlow.update { false }
        _remindDeviceBeyondMapFlow.update { false }
        prefDataStore.saveMapSizeChangeReminderMe(false)
    }

    fun closeRemind() = viewModelScope.launch {
        _remindDeviceBeyondMapFlow.update { false }
    }

    private val _showAvgPer: MutableStateFlow<Boolean> = MutableStateFlow(false)
    val showAvgPer: StateFlow<Boolean> = _showAvgPer.asStateFlow()
    fun toggleShowAvgPer() {
        _showAvgPer.update { !_showAvgPer.value }
    }

    private val _highlightDevice: MutableStateFlow<MapDeviceDto?> = MutableStateFlow(null)
//    val highlightDevice: StateFlow<MapDeviceDto?> = _highlightDevice.asStateFlow()
    fun highlightDevice(dto: MapDeviceDto?) = viewModelScope.launch {
        // TODO On RSSI Map page, the app highlights the relevant routes (or greys out irrelevant routes) when user taps one unit ID (this is kind of filter feature). The app goes back to normal display if user taps other areas.
        _highlightDevice.update { dto }
    Timber.i("1111111111111  highlightDevice    filterLineAndDevice")
        filterLineAndDevice()
    }
//
//    fun reloadLineFlow() = viewModelScope.launch {
//        _lineFlow.value.forEach { lineDto ->
//            lineDto.wsnDev.dateTime = lineDto.wsnDev.dateTime +1
//        }
//        delay(10)
//        //页面在课件不可见切换后，line显示有异常（会短时不显示），这里强制更新一下
//        filterLineAndDevice()
//    }

    private val _showLineFrom: MutableStateFlow<Long> = MutableStateFlow(-1)
//    val showLineFrom: StateFlow<Long> = _showLineFrom.asStateFlow()
    fun showLineFromNow() = viewModelScope.launch {
//        Timber.i("------------------showLineFromNow 111111111------------------  %s", System.currentTimeMillis().ymdHMS())
        _showLineFrom.update {
            System.currentTimeMillis()
        }

        _avgPerList.clear()
        _avgPerDataFlow.update { mutableListOf() }
        FhcFlowEventBus.publish(FlowEventBusData(EventType.RssiDataFrom, RssiDataFromDto()))
         Timber.i("1111111111111  showLineFromNow    filterLineAndDevice")
        filterLineAndDevice()
    }

    private val _lineFilterFlow: MutableStateFlow<MutableList<MapDeviceLineDto>> = MutableStateFlow(mutableStateListOf())
    val lineFilterFlow: StateFlow<MutableList<MapDeviceLineDto>> = _lineFilterFlow.asStateFlow()


    private fun isDeviceIdMatchFullRoute(lineDto:  WsnDeviceRssiDto): Boolean {
        return lineDto.fromDevId+RouteJoin+lineDto.toDevId in devFilterAllRoutes
    }


    var devFilterAllRoutes: MutableList<String> = mutableListOf()
    private  fun getDevFilterAllRoutes(){
        devFilterAllRoutes = mutableListOf()
        viewModelScope.launch {
            if(filterState.value.isFilterDevIds && filterState.value.devIds.trim().isNotEmpty()){
                val arr = filterState.value.devIds.trim().split("\\s+".toRegex()).filter { it.isNotEmpty() }
                if( arr.isNotEmpty()){
                    val listRssi = rssiHisRepo.getAllParseIncludes("", 0, arr)
                    listRssi.forEachIndexed { _, part ->
                        //数据以BC42 --> A912,A912 --> C973,C973 --> 7FFF, 格式存放，每一组包含fromDevId  toDevId
                        val data = part.split(",").filter { it.isNotEmpty() }
                        val uniqueData = data.filter { !devFilterAllRoutes.contains(it) } // 过滤掉已存在的元素
                        devFilterAllRoutes.addAll(uniqueData)
                    }
                }
            }
        }

    }
    /**
     * Filter line and device
     *
     * 当过滤设备ID为空时，恢复显示所有设备和连线。
     * 当输入过滤条件时，按空白字符分割成数组并进行大小写不敏感的匹配。line中包含任何设备ID的line都会被保留。
     * 收集line所有匹配的设备ID（包括line的起点和终点）。
     * 根据收集到的设备ID过滤设备列表。
     */
    private fun filterLineAndDevice() {
        // 使用互斥锁避免并发修改异常
        viewModelScope.launch {
            listMutex.withLock {
                val lineListCopy = _lineFlow.value.map { it.copy() }
                lineListCopy.forEach { lineDto ->
                    lineDto.isUpdatedIn1s = (System.currentTimeMillis() - lineDto.wsnDev.dateTime) <= 1000
                    lineDto.isNoUpdate60s = (System.currentTimeMillis() - lineDto.wsnDev.dateTime) > 60 * 1000
                    lineDto.isLineShow =   lineDto.wsnDev.dateTime - _showLineFrom.value > 0

                    lineDto.isUnFocused = false
                    _highlightDevice.value?.let {
                        lineDto.isUnFocused = lineDto.wsnDev.fromDevId != it.devId && lineDto.wsnDev.toDevId != it.devId
                    }
                }

                val lineList = lineListCopy.filter { lineDto ->
                    if (_filterState.value.isFilterDevIds && _filterState.value.isFilterRssi) {
                        (isDeviceIdMatch(lineDto.wsnDev) || isDeviceIdMatchFullRoute(lineDto.wsnDev))  && isRssiMatch(lineDto.wsnDev)
                    } else if (_filterState.value.isFilterDevIds) {
                        (isDeviceIdMatch(lineDto.wsnDev) || isDeviceIdMatchFullRoute(lineDto.wsnDev))
                    } else if (_filterState.value.isFilterRssi) {
                        isRssiMatch(lineDto.wsnDev)
                    } else {
                        true
                    }
                }
                val devIDs = lineList
                    .flatMap { listOf(it.wsnDev.fromDevId, it.wsnDev.toDevId) }
                    .filter { it.isNotBlank() }
                    .distinct()
                    .toList()

                val devList = _devices.filter { dev ->
                    dev.devId in devIDs
                }
                val devListCopy = devList.map { it.copy() }
                devListCopy.forEach { device->

                    //查找device关联的router
                    val devLines = lineListCopy.filter {
                        it.wsnDev.fromDevId == device.devId || it.wsnDev.toDevId == device.devId
                    }
                    //查找device关联的router一分钟内更新的router
                    val devLines60sUpdated = devLines.filter {
                        System.currentTimeMillis() - it.wsnDev.dateTime < 60 * 1000
                    }
                    device.isNoUpdate60s = devLines60sUpdated.isEmpty()
                    if(device.isNoUpdate60s ){
                        //一分钟内未更新的router，1.5秒内rssi必然没有Updated
                        device.rssiUpdated = false
                    }else{
                        val devRssiLinesUpdated = devLines.filter {
                            System.currentTimeMillis() - it.wsnDev.dateTime < 1500
                        }
                        device.rssiUpdated = devRssiLinesUpdated.isNotEmpty()
                    }
                    var unHighlight: Boolean
                    if(_highlightDevice.value != null){
                        unHighlight = true
                        val highlightDevId = _highlightDevice.value!!.devId
                        if(device.devId != highlightDevId) {
                            //首先查找所有包含选中device的line
                            //然后查找line中包含的devices是否含有当前循环的device
                            val lines = lineListCopy.filter {
                                (it.wsnDev.dateTime - _showLineFrom.value) > 0 && (it.wsnDev.fromDevId == highlightDevId || it.wsnDev.toDevId == highlightDevId)
                            }
                            val devInRelatedLine = lines.find { it.wsnDev.fromDevId == device.devId || it.wsnDev.toDevId == device.devId }
                            if(devInRelatedLine != null){
                                unHighlight = false
                            }
                        }else{
                            unHighlight = false
                        }
                    }else{
                        unHighlight = false
                    }
                    device.unHighlight = unHighlight
                }

                _devFilterFlow.update { devListCopy.toMutableList() }
                _lineFilterFlow.update { lineList.toMutableList() }
            }
        }
    }

    /**
     * 定时计算平均PER
     */
    private fun resetLineDeviceState(): Job {
       return viewModelScope.launch {
            while (isActive) {
                withContext(dispatcher) {
//                    val devListCopy = _devFilterFlow.value.map { it.copy() }
//                    devListCopy.forEach { device->
//                        if(device.rssiUpdated){
//                            val lineDto = _lineFlow.value.find { it.wsnDev.fromDevId == device.devId || it.wsnDev.toDevId == device.devId}
//                            if(lineDto != null){
//                                device.rssiUpdated = (System.currentTimeMillis() - lineDto.wsnDev.dateTime) < 3000
//                                device.isNoUpdate60s = (System.currentTimeMillis() - lineDto.wsnDev.dateTime) > 60 * 1000
//                            }else{
//                                device.rssiUpdated = false
//                                device.isNoUpdate60s = true
//                            }
//                        }
//                    }
//                    _devFilterFlow.update { devListCopy.toMutableList() }
//
//                    val lineListCopy = _lineFlow.value.map { it.copy() }
//                    lineListCopy.forEach { lineDto->
//                        lineDto.isNoUpdate60s = (System.currentTimeMillis() - lineDto.wsnDev.dateTime) > 60 * 1000
//                    }
//                    _lineFlow.update { lineListCopy.toMutableList() }
                    Timber.i("1111111111111  resetLineDeviceState    filterLineAndDevice")

                    filterLineAndDevice()
                    delay(1010L)
                }
            }
        }
    }
    override fun clearAllData() {
        _avgPerDataFlow.update { mutableListOf() }
        super.clearAllData()
    }

    override fun onCleared() {
        super.onCleared()
        resetDeviceStateJob?.cancel()// 自动在ViewModel销毁时取消
        resetDeviceStateJob = null
    }
}
